package com.cskaoyan.service;

import com.cskaoyan.bean.*;
import com.cskaoyan.bean.bo.WxGoodsListBO;
import com.cskaoyan.bean.common.CommonData;
import com.cskaoyan.bean.vo.*;
import com.cskaoyan.mapper.*;
import com.github.pagehelper.PageHelper;
import lombok.AllArgsConstructor;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * \* User: 余雨健
 * \* Date: 2022/10/14
 * \* Time: 19:38
 **/
@Service
public class WxGoodsServiceImpl implements WxGoodsService {

    @Autowired
    MarketGoodsMapper marketGoodsMapper;
    @Autowired
    MarketCategoryMapper marketCategoryMapper;
    @Autowired
    MarketGoodsAttributeMapper marketGoodsAttributeMapper;
    @Autowired
    MarketBrandMapper marketBrandMapper;
    @Autowired
    MarketCommentMapper marketCommentMapper;
    @Autowired
    MarketGrouponRulesMapper marketGrouponRulesMapper;
    @Autowired
    MarketIssueMapper marketIssueMapper;
    @Autowired
    MarketGoodsProductMapper marketGoodsProductMapper;
    @Autowired
    MarketGoodsSpecificationMapper marketGoodsSpecificationMapper;
    @Autowired
    MarketCollectMapper marketCollectMapper;
    @Autowired
    MarketSearchHistoryMapper marketSearchHistoryMapper;
    @Autowired
    MarketFootprintMapper marketFootprintMapper;

    @Override
    public int selectGoodsCount() {
        MarketGoodsExample marketGoodsExample = new MarketGoodsExample();
        List<MarketGoods> marketGoods = marketGoodsMapper.selectByExample(marketGoodsExample);
        int size = marketGoods.size();
        return size;
    }

    @Override
    public WxGoodsCategoryVO selectCategory(Integer id) {
        Integer ids = id;
        WxGoodsCategoryVO wxGoodsCategoryVO = new WxGoodsCategoryVO();
        MarketCategory marketCategory2 = marketCategoryMapper.selectByPrimaryKey(id);
        MarketCategoryExample marketCategoryExample = new MarketCategoryExample();
        if (marketCategory2.getPid() != 0) {
            ids = marketCategory2.getPid();
            MarketCategoryExample.Criteria criteria = marketCategoryExample.createCriteria();
            criteria.andPidEqualTo(ids);
        } else {
            MarketCategoryExample.Criteria criteria = marketCategoryExample.createCriteria();
            criteria.andPidEqualTo(ids);
        }
        List<MarketCategory> marketCategories = marketCategoryMapper.selectByExample(marketCategoryExample);
        wxGoodsCategoryVO.setBrotherCategory(marketCategories);
        if (marketCategory2.getPid() != 0) {
            MarketCategory marketCategory = marketCategoryMapper.selectByPrimaryKey(id);
            wxGoodsCategoryVO.setCurrentCategory(marketCategory);
        } else {
            MarketCategory marketCategory = marketCategoryMapper.selectByPrimaryKey(marketCategories.get(0).getId());
            wxGoodsCategoryVO.setCurrentCategory(marketCategory);
        }
        MarketCategory marketCategory1 = marketCategoryMapper.selectByPrimaryKey(ids);
        wxGoodsCategoryVO.setParentCategory(marketCategory1);
        return wxGoodsCategoryVO;
    }

    @Override
    public WxGoodsListVO selectGoodsList(WxGoodsListBO wxGoodsListBO) {
//        PageHelper.startPage(wxGoodsListBO.getPage(),wxGoodsListBO.getLimit());
        WxGoodsListVO wxGoodsListVO = new WxGoodsListVO();
        MarketGoodsExample marketGoodsExample = new MarketGoodsExample();
        MarketGoodsExample.Criteria criteria1 = marketGoodsExample.createCriteria();
        if (wxGoodsListBO.getCategoryId() != null) {
            if (wxGoodsListBO.getCategoryId() > 0) {
                criteria1.andCategoryIdEqualTo(wxGoodsListBO.getCategoryId());
            }
        }
        if (wxGoodsListBO.getOrder() != null && wxGoodsListBO.getSort() != null) {
            marketGoodsExample.setOrderByClause(wxGoodsListBO.getSort() + " " + wxGoodsListBO.getOrder());
        }
        if (wxGoodsListBO.getKeyword() != null) {
            // 搜索和显示商品调用的是同一个方法，但只有搜索需要用到keyword，所以，当keyword不为null时，要往数据库中写入历史搜索记录
            String keyword = wxGoodsListBO.getKeyword();
            criteria1.andNameLike("%" + keyword + "%");

            // 获取用户id
            Subject subject = SecurityUtils.getSubject();
            PrincipalCollection principals = subject.getPrincipals();
            // 如果不登陆就不记录历史搜索
            if (principals != null) {
                MarketUser user = (MarketUser) principals.getPrimaryPrincipal();
                Integer userId = user.getId();

                // 查找搜索历史记录中有没有这个关键词
                MarketSearchHistoryExample marketSearchHistoryExample = new MarketSearchHistoryExample();
                MarketSearchHistoryExample.Criteria criteria = marketSearchHistoryExample.createCriteria();
                criteria.andKeywordEqualTo(keyword);
                List<MarketSearchHistory> marketSearchHistories = marketSearchHistoryMapper.selectByExample(marketSearchHistoryExample);

                // 如果没有历史记录，新建，有的话，更新
                if (marketSearchHistories.size() == 0) {
                    MarketSearchHistory marketSearchHistory = new MarketSearchHistory();
                    marketSearchHistory.setUserId(userId);
                    marketSearchHistory.setKeyword(wxGoodsListBO.getKeyword());
                    marketSearchHistory.setFrom("");
                    Date date = new Date();
                    marketSearchHistory.setAddTime(date);
                    marketSearchHistory.setUpdateTime(date);
                    marketSearchHistory.setDeleted(false);
                    marketSearchHistoryMapper.insert(marketSearchHistory);
                } else {
                    Integer id = marketSearchHistories.get(0).getId();
                    MarketSearchHistory marketSearchHistory = new MarketSearchHistory();
                    marketSearchHistory.setId(id);
                    marketSearchHistory.setUpdateTime(new Date());
                    marketSearchHistoryMapper.updateByPrimaryKeySelective(marketSearchHistory);
                }
            }
        }

        if (wxGoodsListBO.getBrandId() != null) {
            criteria1.andBrandIdEqualTo(wxGoodsListBO.getBrandId());
        }
        List<MarketGoods> marketGoods = marketGoodsMapper.selectByExample(marketGoodsExample);
        if (marketGoods == null) {
            wxGoodsListVO.setList(null);
        } else {
            wxGoodsListVO.setList(marketGoods);
        }
        int total = marketGoods.size();
        Integer page = wxGoodsListBO.getPage();
        Integer limit = wxGoodsListBO.getLimit();
        int papes = (total + limit - 1) / limit;
        List<MarketCategory> marketCategories = new ArrayList<>();
        if (wxGoodsListBO.getKeyword() != null) {
            List<Integer> categoryId = new ArrayList<>();
            for (MarketGoods goods : marketGoods) {
                if (!categoryId.contains(goods.getCategoryId())) {
                    categoryId.add(goods.getCategoryId());
                }
            }
            for (Integer integer : categoryId) {
                MarketCategory marketCategory = marketCategoryMapper.selectByPrimaryKey(integer);
                marketCategories.add(marketCategory);
            }
            wxGoodsListVO.setFilterCategoryList(marketCategories);
        } else if (wxGoodsListBO.getBrandId() != null) {
            List<Integer> categoryIdList = new ArrayList<>();
            for (MarketGoods goods : marketGoods) {
                if (!categoryIdList.contains(goods.getCategoryId())) {
                    categoryIdList.add(goods.getCategoryId());
                }
            }
            List<MarketCategory> list = new ArrayList<>();
            for (Integer integer : categoryIdList) {
                MarketCategory marketCategory = marketCategoryMapper.selectByPrimaryKey(integer);
                list.add(marketCategory);
            }
            wxGoodsListVO.setFilterCategoryList(list);
        } else {
            MarketCategory marketCategory = marketCategoryMapper.selectByPrimaryKey(wxGoodsListBO.getCategoryId());
            if (marketCategory.getPid() != 0) {
                MarketCategoryExample marketCategoryExample = new MarketCategoryExample();
                MarketCategoryExample.Criteria criteria = marketCategoryExample.createCriteria();
                criteria.andPidNotEqualTo(marketCategory.getPid());
                List<MarketCategory> marketCategories1 = marketCategoryMapper.selectByExample(marketCategoryExample);
                wxGoodsListVO.setFilterCategoryList(marketCategories1);
            } else {
                MarketCategoryExample marketCategoryExample = new MarketCategoryExample();
                MarketCategoryExample.Criteria criteria = marketCategoryExample.createCriteria();
                criteria.andPidNotEqualTo(marketCategory.getId());
                List<MarketCategory> marketCategories1 = marketCategoryMapper.selectByExample(marketCategoryExample);
                wxGoodsListVO.setFilterCategoryList(marketCategories1);
            }
        }
        wxGoodsListVO.setLimit(limit);
        wxGoodsListVO.setPage(page);
        wxGoodsListVO.setPages(papes);
        wxGoodsListVO.setTotal(total);
        return wxGoodsListVO;
    }

    @Override
    public WxGoodsDetailVO returnGoodsDetail(Integer id) {
        WxGoodsDetailVO wxGoodsDetailVO = new WxGoodsDetailVO();
        //info
        MarketGoods marketGoods = marketGoodsMapper.selectByPrimaryKey(id);
        wxGoodsDetailVO.setInfo(marketGoods);
        //attribute
        MarketGoodsAttributeExample marketGoodsAttributeExample = new MarketGoodsAttributeExample();
        MarketGoodsAttributeExample.Criteria criteria = marketGoodsAttributeExample.createCriteria();
        criteria.andGoodsIdEqualTo(id);
        List<MarketGoodsAttribute> marketGoodsAttributes = marketGoodsAttributeMapper.selectByExample(marketGoodsAttributeExample);
        wxGoodsDetailVO.setAttribute(marketGoodsAttributes);
        //brand
        MarketBrand marketBrand = marketBrandMapper.selectByPrimaryKey(marketGoods.getBrandId());
        wxGoodsDetailVO.setBrand(marketBrand);

        //comment
        MarketCommentExample marketCommentExample = new MarketCommentExample();
        MarketCommentExample.Criteria criteria1 = marketCommentExample.createCriteria();
        criteria1.andTypeEqualTo((byte) 0);
        criteria1.andValueIdEqualTo(id);
        List<MarketComment> marketComments = marketCommentMapper.selectByExample(marketCommentExample);
        int count = marketComments.size();
        if (count > 2) {
            List<MarketComment> trueComments = new ArrayList<>();
            for (int i = count - 1; i > count - 3; i--) {
                trueComments.add(marketComments.get(i));
            }
            WxGoodsDetailCommentVO wxGoodsDetailCommentVO = new WxGoodsDetailCommentVO(count, trueComments);
            wxGoodsDetailVO.setComment(wxGoodsDetailCommentVO);
        } else {
            WxGoodsDetailCommentVO wxGoodsDetailCommentVO = new WxGoodsDetailCommentVO(count, marketComments);
            wxGoodsDetailVO.setComment(wxGoodsDetailCommentVO);
        }
        //groupon
        MarketGrouponRulesExample marketGrouponRulesExample = new MarketGrouponRulesExample();
        MarketGrouponRulesExample.Criteria criteria2 = marketGrouponRulesExample.createCriteria();
        criteria2.andGoodsIdEqualTo(id);
        List<MarketGrouponRules> marketGrouponRules = marketGrouponRulesMapper.selectByExample(marketGrouponRulesExample);
        wxGoodsDetailVO.setGroupon(marketGrouponRules);
        //issue
        MarketIssueExample marketIssueExample = new MarketIssueExample();
        List<MarketIssue> marketIssues = marketIssueMapper.selectByExample(marketIssueExample);
        wxGoodsDetailVO.setIssue(marketIssues);
        //productList
        MarketGoodsProductExample marketGoodsProductExample = new MarketGoodsProductExample();
        MarketGoodsProductExample.Criteria criteria3 = marketGoodsProductExample.createCriteria();
        criteria3.andGoodsIdEqualTo(id);
        List<MarketGoodsProduct> marketGoodsProducts = marketGoodsProductMapper.selectByExample(marketGoodsProductExample);
        wxGoodsDetailVO.setProductList(marketGoodsProducts);
        //share
        //shareImage
        if (marketGoods.getShareUrl() != null) {
            wxGoodsDetailVO.setShare(true);
            wxGoodsDetailVO.setShareImage(marketGoods.getShareUrl());
        } else {
            wxGoodsDetailVO.setShare(false);
            wxGoodsDetailVO.setShareImage("");
        }
        //specificationList
        MarketGoodsSpecificationExample marketGoodsSpecificationExample = new MarketGoodsSpecificationExample();
        MarketGoodsSpecificationExample.Criteria criteria4 = marketGoodsSpecificationExample.createCriteria();
        criteria4.andGoodsIdEqualTo(id);
        List<MarketGoodsSpecification> marketGoodsSpecifications = marketGoodsSpecificationMapper.selectByExample(marketGoodsSpecificationExample);
        List<WxGoodsDetailSpecificationListVO> listVOS = new ArrayList<>();
        String specification = marketGoodsSpecifications.get(0).getSpecification();
        List<String> stringList = new ArrayList<>();
        stringList.add(specification);
        for (MarketGoodsSpecification marketGoodsSpecification : marketGoodsSpecifications) {
            String specification1 = marketGoodsSpecification.getSpecification();
            if (stringList.contains(specification1)) {
                continue;
            } else {
                stringList.add(specification1);
            }
        }
        for (String s : stringList) {
            List<MarketGoodsSpecification> list = new ArrayList<>();
            for (MarketGoodsSpecification marketGoodsSpecification1 : marketGoodsSpecifications) {
                if (s.equals(marketGoodsSpecification1.getSpecification())) {
                    list.add(marketGoodsSpecification1);
                }
            }
            WxGoodsDetailSpecificationListVO wxGoodsDetailSpecificationListVO1 = new WxGoodsDetailSpecificationListVO(s, list);
            listVOS.add(wxGoodsDetailSpecificationListVO1);
        }
        wxGoodsDetailVO.setSpecificationList(listVOS);


        //userHasCollect
        MarketCollectExample marketCollectExample = new MarketCollectExample();
        MarketCollectExample.Criteria criteria5 = marketCollectExample.createCriteria();
        //获取用户id
        //MarketUser marketUser = (MarketUser)SecurityUtils.getSubject().getPrincipals().getPrimaryPrincipal();
        PrincipalCollection principals = SecurityUtils.getSubject().getPrincipals();
        MarketUser marketUser = null;

        marketUser = (MarketUser) principals.getPrimaryPrincipal();
        Integer userId = marketUser.getId();
        criteria5.andUserIdEqualTo(userId);


        criteria5.andTypeEqualTo((byte) 0);
        criteria5.andValueIdEqualTo(id);
        //criteria5.andDeletedEqualTo(false);

        List<MarketCollect> marketCollects = marketCollectMapper.selectByExample(marketCollectExample);
        if (marketCollects != null && marketCollects.size() > 0) {
            MarketCollect marketCollect = marketCollects.get(0);
            Boolean deleted = marketCollect.getDeleted();
            if (deleted) {
                wxGoodsDetailVO.setUserHasCollect(0);
            } else {
                wxGoodsDetailVO.setUserHasCollect(1);
            }
        }

        //int size = marketCollects.size();
        // wxGoodsDetailVO.setUserHasCollect(size);
        MarketFootprintExample marketFootprintExample = new MarketFootprintExample();
        MarketFootprintExample.Criteria footprintExampleCriteria = marketFootprintExample.createCriteria();
        footprintExampleCriteria.andUserIdEqualTo(userId);
        footprintExampleCriteria.andDeletedEqualTo(false);
        //查询出该用户的浏览足迹
        List<MarketFootprint> marketFootprints = marketFootprintMapper.selectByExample(marketFootprintExample);

        // if(marketFootprints==null || marketFootprints.size()==0){
        //     //该用户没有浏览记录，直接插入
        //     Date date = new Date();
        //     MarketFootprint marketFootprint3 = new MarketFootprint();
        //     marketFootprint3.setUserId(userId);
        //     marketFootprint3.setGoodsId(id);
        //     marketFootprint3.setAddTime(date);
        //     marketFootprint3.setUpdateTime(date);
        //     marketFootprintMapper.insertSelective(marketFootprint3);
        // }else{
        //     //存在浏览记录，判断是否有重复的
        //     boolean flag=true;
        //     for (MarketFootprint marketFootprint : marketFootprints) {
        //         Date addTime = marketFootprint.getAddTime();
        //         SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        //         String addTimeStr = sdf.format(addTime);
        //         String now = sdf.format(new Date());
        //         //只有当商品id相同，并且是同一天添加的，才认为是重复的
        //         if(marketFootprint.getGoodsId().equals(id) && addTimeStr.equals(now)){
        //             //重复
        //             flag=false;
        //
        //             //更新时间
        //             marketFootprintExample.clear();
        //             MarketFootprintExample.Criteria criteria6 = marketFootprintExample.createCriteria();
        //             criteria6.andUserIdEqualTo(userId);
        //             criteria6.andGoodsIdEqualTo(id);
        //             criteria6.andAddTimeEqualTo(addTime);
        //             criteria6.andDeletedEqualTo(false);
        //             Date date = new Date();
        //             MarketFootprint marketFootprint1 = new MarketFootprint();
        //             marketFootprint1.setUpdateTime(date);
        //             marketFootprintMapper.updateByExampleSelective(marketFootprint1, marketFootprintExample);
        //         }
        //     }
        //     if(flag){
        //         //没有重复的，插入新数据
        //         //该用户没有浏览记录，直接插入
        //         Date date = new Date();
        //         MarketFootprint marketFootprint3 = new MarketFootprint();
        //         marketFootprint3.setUserId(userId);
        //         marketFootprint3.setGoodsId(id);
        //         marketFootprint3.setAddTime(date);
        //         marketFootprint3.setUpdateTime(date);
        //         marketFootprintMapper.insertSelective(marketFootprint3);
        //     }
        // }


        boolean flag = true;
        if (marketFootprints != null) {
            for (MarketFootprint marketFootprint : marketFootprints) {
                Date addTime = marketFootprint.getAddTime();
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
                String addTimeStr = sdf.format(addTime);
                String now = sdf.format(new Date());
                if (marketFootprint.getGoodsId().equals(id) && addTimeStr.equals(now)) {
                    flag = false;
                    marketFootprintExample.clear();
                    MarketFootprintExample.Criteria criteria6 = marketFootprintExample.createCriteria();
                    criteria6.andUserIdEqualTo(userId);
                    criteria6.andGoodsIdEqualTo(id);
                    criteria6.andAddTimeEqualTo(addTime);
                    Date date = new Date();
                    MarketFootprint marketFootprint1 = new MarketFootprint();
                    marketFootprint1.setUpdateTime(date);
                    marketFootprintMapper.updateByExampleSelective(marketFootprint1, marketFootprintExample);
                }
            }
        }
        if (flag) {
            Date date = new Date();
            MarketFootprint marketFootprint3 = new MarketFootprint();
            marketFootprint3.setUserId(userId);
            marketFootprint3.setGoodsId(id);
            marketFootprint3.setAddTime(date);
            marketFootprint3.setUpdateTime(date);
            marketFootprintMapper.insertSelective(marketFootprint3);
        }
        return wxGoodsDetailVO;
     }

    @Override
    public CommonData<MarketGoods> selectGoodsRelated(Integer id) {
        CommonData<MarketGoods> marketGoodsCommonData = new CommonData<>();
        Random random = new Random();
        int limit = 6;
        int page = 1;
        MarketGoods marketGoods = marketGoodsMapper.selectByPrimaryKey(id);
        Integer categoryId = marketGoods.getCategoryId();
        MarketGoodsExample marketGoodsExample = new MarketGoodsExample();
        MarketGoodsExample.Criteria criteria = marketGoodsExample.createCriteria();
        criteria.andCategoryIdEqualTo(categoryId);
        criteria.andIdNotEqualTo(id);
        List<MarketGoods> marketGoods1 = marketGoodsMapper.selectByExample(marketGoodsExample);
        int total = marketGoods1.size();
        int papes = (total + limit - 1) / limit;
        if (total > 6) {
            List<MarketGoods> marketGoods2 = new ArrayList<>();
            for (int i = 0; i < 6; i++) {
                int randomIndex = random.nextInt(marketGoods1.size());
                MarketGoods marketGoods3 = marketGoods1.get(randomIndex);
                marketGoods1.remove(randomIndex);
                marketGoods2.add(marketGoods3);
            }
            marketGoodsCommonData.setList(marketGoods2);
            marketGoodsCommonData.setTotal(total);
            marketGoodsCommonData.setLimit(limit);
            marketGoodsCommonData.setPage(page);
            marketGoodsCommonData.setPages(papes);
        } else {
            marketGoodsCommonData.setList(marketGoods1);
            marketGoodsCommonData.setTotal(total);
            marketGoodsCommonData.setLimit(limit);
            marketGoodsCommonData.setPage(page);
            marketGoodsCommonData.setPages(papes);
        }
        return marketGoodsCommonData;
    }
}

